// upload 封装
import { createElement } from 'react'
import { Upload, message } from 'antd'
const { Dragger } = Upload

const h = createElement;
const BYTE = 1024
const ACCEPT = {
  fa: 'fa',
  xml: 'xml',
  gb: 'gb',
}
const getAccepts = accept => (Array.isArray(accept) ? accept : [accept]).map(ac => ACCEPT[ac]).join(',')
const beforeCheck = (config, file, sequenceData, fileList) => {
  if (fileList.length > 1) {
    window.toastr.warning(`仅允许上传一个文件`)
    return false
  }
  let { accept, max = Number.MAX_VALUE } = config || {}
  const { type } = sequenceData
  console.log('type=>', type);
  let { size, name } = file
  let fileName = name;
  let pos = fileName.lastIndexOf("."); // 获取字符串最后出现的位置
  let lastName = null
  if (pos) {
    lastName = fileName.substring(pos + 1, fileName.length); // 截取字符串
  }
  if (lastName) {
    if (![...accept].includes(lastName.toLowerCase())) {
      const acceptStr = accept.join(', ')
      window.toastr.warning(`文件必须为${acceptStr}类型`);
      return false;
    }
  }
  //大小限制(M)
  const isGtMaxSize = size / BYTE / BYTE <= max
  if (!isGtMaxSize && max) {
    message.info(`文件不能超过${max}M`);
    return false
  }
}

const UploadComponent = props => {
  let { children, config, sequenceData } = props;
  let { accept } = config;
  let attrs = {};

  //不能在props对象上直接添加属性，只能再定义一个attrs对象
  Object.assign(attrs, {
    action: '',
    multiple: true,
    accept: getAccepts(accept),
    beforeUpload: (file, fileList) => beforeCheck(config, file, sequenceData, fileList),
    customRequest: opts => {
      let { file, onSuccess } = opts
      let { type } = file
      let regExp = /image\/[a-z]{2,4}$/i;
      file.isImg = regExp.test(type) ? true : false;
      onSuccess(file)
    }
  })

  return h(Dragger, { ...props, ...attrs }, children)
}

export default UploadComponent